<?php
namespace frontend\controllers;

use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use common\models\UserAuth;
use common\models\User;
use common\models\Banner;
use frontend\controllers\base\BaseController;
use common\models\District;
use common\models\Goods;
use common\models\Record;
use common\models\HelpColumn;
use frontend\models\ResetpwdForm;
use common\models\Link;
use common\models\News;

/**
 * Site controller
 */
class SiteController extends BaseController
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => [
                    'logout',
                    'signup'
                ],
                'rules' => [
                    [
                        'actions' => [
                            'signup'
                        ],
                        'allow' => true,
                        'roles' => [
                            '?'
                        ]
                    ],
                    [
                        'actions' => [
                            'logout'
                        ],
                        'allow' => true,
                        'roles' => [
                            '@'
                        ]
                    ]
                ]
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'send-code'=>[
                        'post'
                    ]
                ]
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction'
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                'maxLength' => 4,
                'minLength' => 4
            ],
            'auth' => [
                
                'class' => 'yii\authclient\AuthAction',
                
                'successCallback' => [
                    $this,
                    'successCallback'
                ]
            ]
            
        ]
        ;
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $this->layout = 'main2.php';
        $banner = Banner::find()->asArray()->all();
        $banner = self::dataSort($banner, 'type');
        if(!Yii::$app->user->isGuest){
            $record=Record::find()->select('pid')->where('uid='.Yii::$app->user->id)->asArray()->all();
            if(!empty($record)){//根据浏览记录查询猜你喜欢商品
                $ids=array_column($record, 'pid');
                $pid=Goods::find()->select('count(pid) as num,pid')->where('id in ('.implode(',',$ids).')')->orderBy('num desc')->groupBy('pid')->asArray()->one();
                if(!empty($pid)){
                    $like=Goods::find()->select('id,name,price,logo')->where('pid='.$pid['pid'])->orderBy('num desc')->limit(10)->asArray()->all();
                }
            }else{
                $like=Goods::find()->select('id,name,price,logo')->orderBy('num desc')->limit(10)->asArray()->all();
            }
        }else{
            $like=Goods::find()->select('id,name,price,logo')->orderBy('num desc')->limit(10)->asArray()->all();
        }
        $cdata=$this->columnData();
        if(!empty($cdata)){
            $cdata=array_column($cdata, null,'id');
        }
        $this->showCart();
        $data=[];
        $news=News::find()->with('newColumn')->orderBy('id desc')->limit(10)->all();
        $column=Yii::$app->view->params['column'];
        if(!empty($column)){
            foreach($column[0] as $val){
                if(!empty($column[$val['id']])){
                    $ids=array_column($column[$val['id']], 'id');
                }
                if(!empty($ids)){
                    $data[$val['id']]=Goods::find()->select('id,name,price,logo')->where(['in','pid',$ids])->orderBy('hot')->limit(10)->asArray()->all();
                }
            }
        }
        $hot=Goods::find()->where('hot=1')->asArray()->all();
        return $this->render('index', [
            'banner' => $banner,
            'hot'=>$hot,
            'data'=>$data,
            'like'=>$like,
            'cdata'=>$cdata,
            'news'=>$news
        ]);
    }
    /**
     * ajax省市联动数据获取
     */
    public function actionArea(){
        $data=District::find()->where(['upid'=>(int)$_POST['pid']])->asArray()->all();
        echo json_encode($data);
        exit;
    }
    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        $this->layout = 'login.php';
        if (! Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model
            ]);
        }
    }
    public function actionResetpwd(){
        $this->layout = 'login.php';
        $model=new ResetpwdForm();
        $flag=false;
        $model->setScenario('name');
        $post=Yii::$app->request->post();
        if($model->load($post) && $model->validate()){
            if(preg_match("/^[1][358][0-9]{9}$/", $model->name)){
                $user=User::find()->where('tel='.$model->name)->one();
            }else{
                $user=User::find()->where('username='.$model->name)->one();
            }
            if(empty($user)){
                $model->addError('name','用户名或者手机号不存在');
            }else{
                $flag=1;
                $model->tel=$user->tel;
                $model->setScenario('code');
                if($model->load($post) && $model->validate()){
                    $code=Yii::$app->session->get('code');
                    if(isset($code[3]) && $code[3]['tel']==$model->tel && $code[3]['code']==$model->code){
                        $flag=2;
                        $model->setScenario('uppwd');
                        if($model->load($post) && $model->validate()){
                            $user->password=md5($model->password);
                            if($user->save(false)){
                                $flag=3;
                            }
                        }
                    }else{
                        $model->addError('code','验证码错误');
                    }
                }
            }
        }
        return $this->render('resetpwd',['model'=>$model,'flag'=>$flag]);
    }
    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();
        
        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending email.');
            }
            
            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model
            ]);
        }
    }
    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $this->layout = 'login.php';
        $model = new SignupForm();
        $code=Yii::$app->session->get('code');
        if ($model->load(Yii::$app->request->post())) {
            if(isset($code[1]) && $code[1]['tel']==$model->tel && $code[1]['code']==$model->code){
                if ($user = $model->signup()) {
                    if (Yii::$app->getUser()->login($user)) {
                        return $this->goHome();
                    }
                }
            }else{
                $model->addError('code','验证码错误');
            }
        }
        
        return $this->render('signup', [
            'model' => $model
        ]);
    }
   

    public function successCallback($client)
    
    {
        $attributes = $client->getUserAttributes();
        $model = new UserAuth();
        $id = $client->getId();
        $uid = $model->find()
            ->where([
            'source_id' => $attributes['id'],
            'source' => $id
        ])
            ->one();
        if (! $uid) {
            return $this->redirect([
                '/site/index',
                'oid' => $attributes['openid'],
                'otype' => $client->getId()
            ]);
        } else {
            Yii::$app->user->login(User::findOne([
                'id' => $uid->uid
            ]), 3600 * 24 * 30);
        }
        
        // 用户的信息在$attributes中，以下是您根据您的实际情况增加的代码
        
        // 如果您同时有QQ互联登录，新浪微博等，可以通过 $client->id 来区别。
    }

    public function actionSendCode($id){
        $url='https://api.miaodiyun.com/20150822/industrySMS/sendSMS';
        $time=date('YmdHis');
        $sid='a6e4f21a2b5d4ee49b449dede7a3d122';
        $token='9832d34754b3483ebe7f9765ef4c073f';
        $code=rand(100000, 999999);
        switch ($id){
            case 1:
                $get=Yii::$app->request->get();
                $tel=$get['tel'];
                $content="【锐锋刀剑】尊敬的用户，您好，您正在注册锐锋刀剑网站，验证码为{$code}，若非本人操作请忽略此短信。 提示：请勿泄露给他人";
            break;
            case 2:
                if(Yii::$app->user->id){
                    $tel=Yii::$app->user->identity->tel;
                }else{
                    echo 2;exit;
                }
                $content="【锐锋刀剑】验证码为{$code}，您正在修改登录密码，请确认是本人操作。";break;
            case 3:
                $get=Yii::$app->request->get();
                if(preg_match("/^[1][358][0-9]{9}$/", $get['name'])){
                    $user=User::find()->where('tel='.$get['name'])->one();
                }else{
                    $user=User::find()->where('username='.$get['name'])->one();
                }
                $tel=$user->tel;
                $content="【锐锋刀剑】验证码为{$code}，您正在找回登录密码，请确认是本人操作。";break;
            case 4:
                if(Yii::$app->user->id){
                    $tel=Yii::$app->user->identity->tel;
                }else{
                    echo 2;exit;
                }
                $content="【锐锋刀剑】验证码为{$code}，您正在修改绑定手机，请确认是本人操作";break;
            case 5:
                $get=Yii::$app->request->get();
                $tel=$get['tel'];
                $content="【锐锋刀剑】验证码为{$code}，您正在绑定新手机，请确认是本人操作。";break;
        }
        $data=[
            'accountSid'=>$sid,
            'smsContent'=>$content,
            'to'=>$tel,
            'timestamp'=>$time,
            'sig'=>md5($sid.$token.$time),
            'respDataType'=>'JSON'];
        $json=$this->curl($url, $data);
        $json=json_decode($json,true);
        if($json['respCode']=='00000'){
            $session=Yii::$app->session;
            if(isset($session['code'])){
                $session['code']+=[$id=>['tel'=>$tel,'code'=>$code]];
            }else{
                $session->set('code',[$id=>['tel'=>$tel,'code'=>$code]]);
            }
            echo 1;exit;
        }
        echo $json['respCode'];
    }
}
